<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="roleList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,i1) in scope.row.children "
              :class="['bd_bottom',i1==0?'bd_top':'','vcenter']"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scope.row,item3.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限 -->
                <!-- :class="[i2==1?'bd_top':'']" -->
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :class="[i2==1?'bd_top':'','vcenter']"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsById(scope.row,item3.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限 -->
                    <el-tag
                      type="warning"
                      v-for="(item3,i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightsById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              @close="setRightDialogClosed"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <!-- show-checkbox   	节点是否可被选择 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%">
      <el-tree
        :data="rightsList"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>



<script>
export default {
  data() {
    return {
      roleList: [],
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      defaultProps: {
        children: "children",
        label: "authName"
      },
      // 里面存放权限的id
      defKeys: [],
      roleId: ""
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    //获取用户列表数据
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      // console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("获取用户数据失败");
      }
      this.roleList = res.data;
      // console.log(this.roleList);
    },
    // 删除用户权限
    async removeRightsById(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(confirmResult);

      if (confirmResult != "confirm") {
        return this.$message.error("删除权限失败");
      }

      // 如果是确定了删除，则发起请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      console.log(res);
      // this.getRoleList();
      role.children = res.data;
    },
    // 分配权限
    async showSetRightDialog(role) {
      this.roleId = role.id;
      // console.log(this.roleId);

      const { data: res } = await this.$http.get("rights/tree");
      // console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("获取权限列表失败");
      }
      this.rightsList = res.data;
      // console.log(this.rightsList);
      this.getLeafKeys(role, this.defKeys);
      this.setRightDialogVisible = true;
    },
    // 通过递归的形式，获取角色下的三级权限的id，并保存到defKeys中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      //如果没有不是三级节点，那么是有children属性的,利用forEach对一级二级节点进行循环

      node.children.forEach(item => {
        this.getLeafKeys(item, arr);
      });
      // 实现分配权限的重置功能   点击关闭对话
    },

    // 关闭分配权限的对话框是将   重置defKeys: [] 数组
    setRightDialogClosed() {
      defKeys: [];
    },
    // 点击确定按钮分配权限
    async allotRights() {
      // getCheckedKeys   目前被选中的节点的 key 所组成的数组
      // getHalfCheckedKeys  目前被半选中的节点的 key 所组成的数组
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      // 点击确定按钮以后得到全选和半选按钮的所有的id值
      // [122, 109, 129, 130, 134, 135];
      // console.log(keys);
      const idStr = keys.join(",");
      // 122,109,129,130,134,135,139
      // console.log(idStr);

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr
        }
      );
      console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功");
      // 刷新页面
      this.getRoleList();
      // 隐藏对话框
      this.setRightDialogVisible = false;
    }
  }
};
</script>



<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bd_top {
  border-top: 1px solid #eee;
}
.bd_bottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>